package com.rlyy.basic.resolver.exception;

import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.springframework.aop.scope.ScopedProxyUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.core.annotation.OrderUtils;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 标注有@ControllerAdvice和@RestControllerAdvice注解的
 * 统一异常处理类的描述对象
 *
 * @author yuanqinglong
 * @since 2020/11/30 9:22
 */
@ToString
@EqualsAndHashCode
public class ControllerAdviceBean implements Ordered {

    /**
     * 当前异常处理类bean名称
     */
    private final Object bean;

    /**
     * bean工厂
     */
    private final BeanFactory beanFactory;

    /**
     * 如果使用了@Order注解 保存order的值 用来排序
     */
    private final int order;


    /**
     * 找到@ControllerAdvice和@RestControllerAdvice注解的bean放到集合中
     */
    public static List<ControllerAdviceBean> findAnnotatedBeans(ApplicationContext context) {
        // AnnotationAwareOrderComparator根据Spring内部定义的各排序接口优先级排序
        return Arrays.stream(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context, Object.class))
                .filter(name -> !ScopedProxyUtils.isScopedTarget(name) && context.findAnnotationOnBean(name, ControllerAdvice.class) != null)
                .map(context::getBean).sorted(AnnotationAwareOrderComparator.INSTANCE)
                .map(bean -> new ControllerAdviceBean(bean, context))
                .collect(Collectors.toList());
    }

    /**
     * 创建统一异常处理Bean 描述对象
     *
     * @param bean        bean
     * @param beanFactory bean工厂
     */
    private ControllerAdviceBean(Object bean, BeanFactory beanFactory) {
        this.bean = bean;
        this.beanFactory = beanFactory;
        Class<?> beanType;
        if (bean instanceof String) {
            String beanName = (String) bean;
            Assert.hasText(beanName, "Bean名称不能为空");
            Assert.notNull(beanFactory, "BeanFactory不能为null");
            if (!beanFactory.containsBean(beanName)) {
                throw new IllegalArgumentException("BeanFactory不包含指定的控制器的Bean");
            }
            beanType = this.beanFactory.getType(beanName);
            this.order = initOrderFromBeanType(beanType);
        } else {
            Assert.notNull(bean, "Bean不能为null");
            this.order = initOrderFromBean(bean);
        }

    }


    private static int initOrderFromBean(Object bean) {
        return (bean instanceof Ordered ? ((Ordered) bean).getOrder() : initOrderFromBeanType(bean.getClass()));
    }

    /**
     * 根据@Order注解进行排序
     *
     * @param beanType bean
     * @return 。
     */
    private static int initOrderFromBeanType(Class<?> beanType) {
        Integer order = null;
        if (beanType != null) {
            order = OrderUtils.getOrder(beanType);
        }
        return (order != null ? order : Ordered.LOWEST_PRECEDENCE);
    }

    public Class<?> getBeanType() {
        Class<?> beanType = (this.bean instanceof String ?
                obtainBeanFactory().getType((String) this.bean) : this.bean.getClass());
        return (beanType != null ? ClassUtils.getUserClass(beanType) : null);
    }


    public Object resolveBean() {
        return (this.bean instanceof String ? obtainBeanFactory().getBean((String) this.bean) : this.bean);
    }

    private BeanFactory obtainBeanFactory() {
        Assert.state(this.beanFactory != null, "未设置BeanFactory");
        return this.beanFactory;
    }


    @Override
    public int getOrder() {
        return order;
    }
}
